package com.xqh.study;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @ClassName LocalJDBCTransApplication
 * @Description jdbc 事务管理
 * @Author xuqianghui
 * @Date 2019/12/28 20:47
 * @Version 1.0
 */
public class LocalJDBCTransApplication {

    private static Logger log = LoggerFactory.getLogger(LocalJDBCTransApplication.class);

    public static void main(String[] args) throws SQLException {

        Connection connection = getConnection();
        connection.setAutoCommit(false);
        String plusSql = "UPDATE T_USER set amount = amount + 100 where username = ?";
        String minsSql = "UPDATE T_USER set amount = amount - 100 where username = ?";
        PreparedStatement ps1 = connection.prepareStatement(plusSql);
        ps1.setString(1,"SuperMan");
        ps1.executeUpdate();

//        if(1 == 2){
//            // 异常 导致 事务回滚
//            throw  new SQLException("some error");
//        }

        PreparedStatement ps2 = connection.prepareStatement(minsSql);
        ps2.setString(1, "BatMan");
        ps2.executeUpdate();

        connection.commit();
        ps1.close();
        ps2.close();
        connection.close();

    }

    public static Connection getConnection() throws SQLException {
        String url = "jdbc:mysql://localhost:3306/dist_trans_course";
        String username = "root";
        String password = "root";
        String driver = "com.mysql.jdbc.Driver";
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            log.error("", e);
        }
        return DriverManager.getConnection(url, username, password);
    }
}
